import React, { Component } from 'react';
import { Image, View, Dimensions, StyleSheet, Platform, ScrollView, Alert, TouchableWithoutFeedback, DeviceEventEmitter } from 'react-native';
import STRING from '../../const_string_zh_CN';
import URL from '../../net/url.js';
import { NavigationActions } from 'react-navigation'
import { connect } from 'react-redux';
import interaction from '../../net/interaction.js';
import { Container, Thumbnail, Text, Button, Icon, Body, List, ListItem, Content, Spinner, CheckBox, Radio } from 'native-base';
const { width, height } = Dimensions.get('window');
const marginTop = Platform.OS === 'ios' ? 20 : 0;
var isSubmit = false;//判断题目是否提交
var correctAnswer = '暂无答案'; //存储正确答案
var subject_id = null;
class question_teacher extends Component {
    static navigationOptions = ({ navigation }) => ({
        title: navigation.state.params.title,
    });
    //js组件的构造函数，js的生命周期
    constructor(props) {
        super(props);
        //state内部维护的一个状态，我们刚开始进来的为空，来加载空的view
        this.state = {
            content: null,
            checkbox: [],
            checkbox_value: [],
            radio: -1,
            radio_value: null,
            Answer: null
        };
    }
    render() {
        const { navigate } = this.props.navigation;
        const { subject } = this.props;
        if (!this.state.content) {
            return this.renderLoadingView();
        }
        if (this.state.content[0].subjectType == '多选') {
            return (
                <Container  >
                    <Content>
                        <List style={StyleSheet.flatten(styles.Container)}>
                            <List style={StyleSheet.flatten(styles.List)}>
                                <ListItem button  >
                                    <Icon name='ios-paper-outline' style={{color:'#28AB91'}}/>
                                    <Body>
                                        <Text style={StyleSheet.flatten(styles.text_style)}>{this.state.content[0].stemInfo}</Text>
                                    </Body>
                                </ListItem>
                            </List>
                            {this.renderContent_checkbox(this.state.content)}
                            <View style={StyleSheet.flatten(styles.flexbox)}>
                                <Text style={StyleSheet.flatten(styles.text_style)}>作答详情：无</Text>
                                <Text style={StyleSheet.flatten(styles.text_style)}>答案详情：{this.state.Answer}</Text>
                            </View>
                        </List>
                        <Button block light style={StyleSheet.flatten(styles.button_default)} onPress={() => { this.checkboxSubmit_onPress(); }}>
                            <Text style={{color:'#fff'}}>提交</Text>
                        </Button>
                    </Content>

                </Container>
            );
        }
        else if (this.state.content[0].subjectType == '单选') {
            return (
                <Container  >
                    <Content >
                        <List style={StyleSheet.flatten(styles.Container)}>
                            <List style={StyleSheet.flatten(styles.List)}>
                                <ListItem button  >
                                    <Icon name='ios-paper-outline' style={{color:'#28AB91'}}/>
                                    <Body>
                                        <Text style={StyleSheet.flatten(styles.text_style)}>{this.state.content[0].stemInfo}</Text>
                                    </Body>
                                </ListItem>
                            </List>
                            {this.renderContent_radio(this.state.content)}
                            <View style={StyleSheet.flatten(styles.flexbox)}>
                                <Text style={StyleSheet.flatten(styles.text_style)}>作答详情：无</Text>
                                <Text style={StyleSheet.flatten(styles.text_style)}>答案详情：{this.state.Answer}</Text>
                            </View>
                        </List>
                        <Button block info style={StyleSheet.flatten(styles.button_default)} onPress={() => { this.radioSubmit_onPress(); }}>
                            <Text style={{color:'#fff'}}>提交</Text>
                        </Button>
                    </Content>

                </Container>
            );

        }
    }
    //加载等待的view
    renderLoadingView() {
        return (
            <Container>
                <Content>
                    <Spinner color='green' />
                </Content>
            </Container>
        );
    }
    //多选题目提交单击事件
    async  checkboxSubmit_onPress() {
        let answerInfoArray = [];
        const { login_info } = this.props
        const { InteractionPushSubjectId } = this.props;
        for (let i = 0; i < this.state.checkbox.length; i++) {
            if (this.state.checkbox[i]) {
                answerInfoArray.push({ 'OnlineClassID': InteractionPushSubjectId.OnlineClassID, 'SendSubjectID': InteractionPushSubjectId.SendSubjectID, 'optionID': this.state.checkbox_value[i], 'userID': login_info.userName, 'subjectID': InteractionPushSubjectId.subjectId });
            }
        }
        let answerInfoString = JSON.stringify(answerInfoArray)
        console.log('多选题目-答案信息表');
        console.log(answerInfoArray);
        console.log(answerInfoString);
        //班级信息不能为空
        if (answerInfoArray.length == 0) {
            Alert.alert('温馨提醒:', '提交选项不能为空');
        }
        else {
            let Interaction = new interaction();
            let studentSubmitAnswer = await Interaction.studentSubmitAnswer(login_info.userName, InteractionPushSubjectId.OnlineClassID, answerInfoString, InteractionPushSubjectId.subjectId, InteractionPushSubjectId.SendSubjectID);
            if (studentSubmitAnswer.errorCode == 0) {
                Alert.alert('温馨提醒:', '提交成功'); isSubmit = true;
            }
            else if (studentSubmitAnswer.errorCode == 1) {
                if (studentSubmitAnswer.messageInfo == 'response closed') {
                    Alert.alert('温馨提醒:', '作答已关闭');
                    Alert.alert('正确答案：', correctAnswer);
                    this.setState({ Answer: correctAnswer, });
                }
                else if (studentSubmitAnswer.messageInfo == 'subject closed') { Alert.alert('温馨提醒:', '题目已关闭'); }
                else if (studentSubmitAnswer.messageInfo == 'course closed') { Alert.alert('温馨提醒:', '课堂已关闭'); }
                else if (studentSubmitAnswer.messageInfo == 'submit again') { Alert.alert('温馨提醒:', '答案不能重复提交'); }

            }
        }
    }
    //单选题目提交单击事件
    async  radioSubmit_onPress() {
        //班级信息不能为空
        if (this.state.radio_value != null) {
            let answerInfoArray = [];
            const { login_info } = this.props
            const { InteractionPushSubjectId } = this.props;
            answerInfoArray.push({ 'OnlineClassID': InteractionPushSubjectId.OnlineClassID, 'SendSubjectID': InteractionPushSubjectId.SendSubjectID, 'optionID': this.state.radio_value, 'userID': login_info.userName, 'subjectID': InteractionPushSubjectId.subjectId });
            let answerInfoString = JSON.stringify(answerInfoArray)
            let Interaction = new interaction();
            let studentSubmitAnswer = await Interaction.studentSubmitAnswer(login_info.userName, InteractionPushSubjectId.OnlineClassID, answerInfoString, InteractionPushSubjectId.subjectId, InteractionPushSubjectId.SendSubjectID);
            if (studentSubmitAnswer.errorCode == 0) {
                Alert.alert('温馨提醒:', '提交成功'); isSubmit = true;
            }
            else if (studentSubmitAnswer.errorCode == 1) {
                if (studentSubmitAnswer.messageInfo == 'response closed') {
                    Alert.alert('温馨提醒:', '作答已关闭');
                    Alert.alert('正确答案：', correctAnswer);
                    isSubmit = true;
                    this.setState({ Answer: correctAnswer, });
                }
                else if (studentSubmitAnswer.messageInfo == 'subject closed') { Alert.alert('温馨提醒:', '题目已关闭'); }
                else if (studentSubmitAnswer.messageInfo == 'course closed') { Alert.alert('温馨提醒:', '课堂已关闭'); }
                else if (studentSubmitAnswer.messageInfo == 'submit again') { Alert.alert('温馨提醒:', '答案不能重复提交'); }
            }
        }
        else {
            Alert.alert('温馨提醒:', '提交选项不能为空');
        }
    }
    //将接口数据呈现在组件上-多选题目
    renderContent_checkbox(array) {
        const { navigate } = this.props.navigation;
        return array.map((v, i) => {
            return (
                <List style={StyleSheet.flatten(styles.card_style)} key={i}>
                    <TouchableWithoutFeedback
                        onPress={() => {
                            let l = this.state.checkbox;
                            let value = this.state.checkbox_value;
                            l[i] = !l[i];
                            value[i] = v.optionTitle;
                            this.setState({ checkbox: l });
                            this.setState({ checkbox_value: value });
                        }}>
                        <ListItem style={StyleSheet.flatten(styles.ListItem)} >
                            <Body style={StyleSheet.flatten(styles.flexDirection)}>
                                <Text style={StyleSheet.flatten(styles.text_style)}>{v.optionTitle}</Text>
                                <Text style={StyleSheet.flatten(styles.text_style)}>{v.optionContent}</Text>
                            </Body>
                            <CheckBox checked={this.state.checkbox[i]} />
                        </ListItem>
                    </TouchableWithoutFeedback>
                </List>
            );
        })
    }
    //将接口数据呈现在组件上-单选题目
    renderContent_radio(array) {
        const { navigate } = this.props.navigation;
        // const { interactionCourse } = this.props; //   const setLoginState  = this.props.setLoginState;
        return array.map((v, i) => {
            return (
                <List style={StyleSheet.flatten(styles.card_style)} key={i}>
                    <TouchableWithoutFeedback
                        onPress={() => {
                            this.setState({ radio: i });
                            this.setState({ radio_value: v.optionTitle });
                        }} >
                        <ListItem style={StyleSheet.flatten(styles.ListItem)} >
                            <Body style={StyleSheet.flatten(styles.flexDirection)}>
                                <Text style={StyleSheet.flatten(styles.text_style)}>{v.optionTitle}</Text>
                                <Text style={StyleSheet.flatten(styles.text_style)}>{v.optionContent}</Text>
                            </Body>
                            <Radio selected={this.state.radio === i ? true : false} />
                        </ListItem>
                    </TouchableWithoutFeedback>
                </List>
            );
        })
    }
    //通过题目id 获取题目详情
    async  componentWillMount() {
        const { InteractionPushSubjectId } = this.props;
        if (isSubmit == true ) { this.setState({ Answer: correctAnswer, }); }
        if (isSubmit == true && subject_id == InteractionPushSubjectId.subjectId) { this.setState({ Answer: correctAnswer, }); }
        if (isSubmit == true && subject_id != InteractionPushSubjectId.subjectId) { isSubmit = false; }
        subject_id == InteractionPushSubjectId.subjectId ;
        this.pushanswer = DeviceEventEmitter.addListener('mipush', (events) => {
            let datatemp = JSON.parse(events.data);
            console.log('公布答案推送消息datatemp');
            if (datatemp.messageType == 'answer') {
                console.log(decodeURI(datatemp.CorrectAnswer));
                correctAnswer = decodeURI(datatemp.CorrectAnswer);
                if (isSubmit == true) {
                    Alert.alert('正确答案：', decodeURI(datatemp.CorrectAnswer));
                    this.setState({ Answer: correctAnswer, });
                }
            }
        });
        let Interaction = new interaction();
        let SubjectOptionInfo = await Interaction.getSubjectInfo(InteractionPushSubjectId.subjectId);
        this.setState({
            content: SubjectOptionInfo,
        });
    }
    componentWillUnmount() {
        this.pushanswer.remove();
    }
}
const styles = StyleSheet.create({
    button_default: {
        marginTop: 40,
        width: width / 4,
        height: 30,
        alignSelf: 'center',
        backgroundColor: '#F0AD4E',
    },
    card_style: {
        marginRight: 0,
        marginLeft: 0,
        backgroundColor: 'white',
    },
    Content: {
        marginTop: 15,
        // backgroundColor:'white',    
    },
    ListItem: {
        paddingLeft: 60,
        height: 40,
    },
    text_style: {
        //fontFamily:'微软雅黑',
        fontSize: 15,
        color: '#353535',
        marginLeft: 10
        // paddingLeft:15, style={{marginLeft:10}}
    },
    view: {
        marginTop: 15,
        backgroundColor: 'white',
        borderBottomWidth: 0.2,
        borderBottomColor: "#cac0c0",
    },
    marginLeft: {
        marginLeft: 10
    },
    Container: {
        // marginTop: 15,
        backgroundColor: 'white',

    },
    List: {
        backgroundColor: 'white',
        marginTop: 15,
    },
    flexDirection: {
        flexDirection: 'row',
    },
    flexbox: {
        marginTop: 15,
        marginBottom: 15,
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-around',
        alignItems: 'center',

    },
});
function mapStateToProps(state) {
    return {
        subject: state.intercation.subject,
        login_info: state.login.login_info,
        InteractionPushSubjectId: state.intercation.InteractionPushSubjectId,
    }
}

function mapDispatchToProps(dispatch) {
    return {
    }
}
const QuestionTeacher = connect(
    mapStateToProps,
    mapDispatchToProps
)(question_teacher)

export default QuestionTeacher;
